package com.imooc.controller;


import com.google.gson.Gson;
import com.imooc.Interceptor.JwtCurrentUserInterceptor;
import com.imooc.base.BaseInfoProperties;
import com.imooc.bo.CreateCompanyBO;
import com.imooc.bo.ModifyCompanyInfoBO;
import com.imooc.bo.QueryCompanyBO;
import com.imooc.bo.ReviewCompanyBO;
import com.imooc.enums.CompanyReviewStatus;
import com.imooc.exception.GraceException;
import com.imooc.feign.UserMicroServiceFeign;
import com.imooc.pojo.Company;
import com.imooc.pojo.CompanyPhoto;
import com.imooc.pojo.Users;
import com.imooc.result.GraceJSONResult;
import com.imooc.result.ResponseStatusEnum;
import com.imooc.service.CompanyService;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.PagedGridResult;
import com.imooc.vo.CompanyInfoVO;
import com.imooc.vo.CompanySimpleVO;
import com.imooc.vo.UsersVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 企业表 前端控制器
 * </p>
 *
 * @author liansen
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/company")
public class CompanyController extends BaseInfoProperties {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserMicroServiceFeign userMicroServiceFeign;

    @PostMapping("/getByFullName")
    public GraceJSONResult getByFullName(@RequestParam("fullName") String fullName){
        if(StringUtils.isBlank(fullName)){
            return GraceJSONResult.errorMsg("参数不能为null");
        }
        Company company = companyService.getByFullName(fullName);
        if(Objects.isNull(company)){
            return GraceJSONResult.ok();
        }
        return GraceJSONResult.ok(company);
    }

    /**
     * 创建公司 状态: 未发起审核  将公司id返回给前端
     */
    @PostMapping("/createNewCompany")
    public GraceJSONResult createNewCompany(@RequestBody @Valid CreateCompanyBO companyBO){
        String dbCompanyId = "";
        if(StringUtils.isBlank(companyBO.getCompanyId())){
            //创建
            dbCompanyId = companyService.createCompany(companyBO);
        }else {
            //此处可能是hr上一次审核失败的企业，再次发起审核，所以该企业是存在的，对企业信息直接修改即可
            dbCompanyId = companyService.resetCompanyReview(companyBO);
        }
        return GraceJSONResult.ok(dbCompanyId);
    }

    /**
     * 根据企业id查询企业基本信息
     * @param companyId 企业id
     * @param withHRCounts 是否需要查询该企业下的hr数量(根据公司Id查询hr数量)
     * @return
     */
    @PostMapping("/getInfo")
    public GraceJSONResult getInfo(@RequestParam("companyId") String companyId, @RequestParam("withHRCounts") boolean withHRCounts){
        if(StringUtils.isBlank(companyId)){
            return null;
        }
        CompanySimpleVO companySimpleVO = getCompany(companyId);
        if(withHRCounts){  //这个是前端传来的，永远是true
            //远程调用用户微服务, 根据companyId查询该公司下绑定的hr数量
            GraceJSONResult result = userMicroServiceFeign.getCountsByCompanyId(companyId);
            Object data = result.getData();
            Long hrCounts = Long.valueOf(data.toString());
            companySimpleVO.setHrCounts(hrCounts);
        }
        return GraceJSONResult.ok(companySimpleVO);
    }

    private CompanySimpleVO getCompany(String companyId) {

        String jsonStr = redisTemplate.opsForValue().get(REDIS_COMPANY_BASE_INFO + ":" + companyId);
        if(StringUtils.isBlank(jsonStr)){
            //查询数据库
            Company company = companyService.getById(companyId);
            if(Objects.isNull(company)){
                return null;
            }
            CompanySimpleVO companySimpleVO = new CompanySimpleVO();
            BeanUtils.copyProperties(company, companySimpleVO);
            redisTemplate.opsForValue().set(REDIS_COMPANY_BASE_INFO + ":" + companyId, new Gson().toJson(companySimpleVO), 8 * 60, TimeUnit.SECONDS);
            return companySimpleVO;
        }else {
            //直接转换成对象即可
            return new Gson().fromJson(jsonStr, CompanySimpleVO.class);
        }
    }


    //提交企业的审核信息  涉及到分布式事务
    @PostMapping("/goReviewCompany")
    @GlobalTransactional //处理分布式事务
    public GraceJSONResult goReviewCompany(@RequestBody @Valid ReviewCompanyBO reviewCompanyBO){
        //将Hr和公司绑定
        GraceJSONResult result = userMicroServiceFeign.bindingHRToCompany(reviewCompanyBO.getHrUserId(), reviewCompanyBO.getRealname(), reviewCompanyBO.getCompanyId());
        String mobile = result.getData().toString();
        reviewCompanyBO.setHrMobile(mobile);
        //修改审核的状态为审核中
        companyService.commitReview(reviewCompanyBO);
        return GraceJSONResult.ok();
    }


    @PostMapping("/information")
    public GraceJSONResult information(@RequestParam("hrUserId") String hrUserId){
        GraceJSONResult result = userMicroServiceFeign.get(hrUserId);
        Object data = result.getData();
        String str = JsonUtils.objectToJson(data);
        UsersVO usersVO = JsonUtils.jsonToPojo(str, UsersVO.class);
        CompanySimpleVO company = getCompany(usersVO.getHrInWhichCompanyId());
        return GraceJSONResult.ok(company);
    }

    @PostMapping("/moreInfo")
    public GraceJSONResult moreInfo(@RequestParam("companyId") String companyId){
        CompanyInfoVO companyMoreInfo = getCompanyMoreInfo(companyId);
        return GraceJSONResult.ok(companyMoreInfo);
    }

    @PostMapping("/modify")
    public GraceJSONResult modify(@RequestBody ModifyCompanyInfoBO companyInfoBO){

        //判断当前用户绑定的企业id,是否和要修改的企业id一致
        checkUser(companyInfoBO.getCurrentUserId(), companyInfoBO.getCompanyId());
        //修改企业信息
        companyService.modify(companyInfoBO);
        //删除redis的缓存数据
        redisTemplate.delete(REDIS_COMPANY_BASE_INFO + ":" + companyInfoBO.getCompanyId());
        redisTemplate.delete(REDIS_COMPANY_MORE_INFO + ":" + companyInfoBO.getCompanyId());

        if(StringUtils.isNotBlank(companyInfoBO.getPhotos())){
            //保存/修改相册
            companyService.saveOrUpdatePhotos(companyInfoBO);
        }

        return GraceJSONResult.ok();
    }

    private void checkUser(String currentUserId, String companyId) {
        if(StringUtils.isBlank(currentUserId)){
            GraceException.display(ResponseStatusEnum.COMPANY_INFO_UPDATED_ERROR);
        }
        GraceJSONResult result = userMicroServiceFeign.get(currentUserId);
        Object data = result.getData();
        String userJson = JsonUtils.objectToJson(data);
        UsersVO usersVO = JsonUtils.jsonToPojo(userJson, UsersVO.class);
        if(!Objects.isNull(usersVO) && !usersVO.getHrInWhichCompanyId().equals(companyId)){
            GraceException.display(ResponseStatusEnum.COMPANY_INFO_UPDATED_ERROR);
        }
    }

    @PostMapping("/getPhotos")
    public GraceJSONResult getPhotos(@RequestParam("companyId") String companyId){
        CompanyPhoto companyPhoto = companyService.getPhotos(companyId);
        return GraceJSONResult.ok(companyPhoto);
    }


//--------------------------------------  运营端使用---------------------------------------

    //通过xml的sql方式实现
    @PostMapping("/admin/getCompanyList")
    public GraceJSONResult list(@RequestBody QueryCompanyBO companyBO, Integer page, Integer limit){
        if(page == null){
            page = 1;
        }
        if(limit == null){
            limit = 10;
        }
        PagedGridResult result = companyService.queryCompanyListPaged(companyBO, page, limit);
        return GraceJSONResult.ok(result);
    }


    //将上一个方法用代码形式实现
    @PostMapping("/admin/getCompanyListByData")
    public GraceJSONResult getListAll(@RequestBody QueryCompanyBO companyBO, @RequestParam("page") Integer page, @RequestParam("limit") Integer limit){
        if(page == null){
            page = 1;
        }
        if(limit == null){
            limit = 10;
        }
        PagedGridResult result = companyService.getListAll(companyBO, page, limit);
        return GraceJSONResult.ok(result);
    }


    //查询公司详情
    @PostMapping("/admin/getCompanyInfo")
    public GraceJSONResult getCompanyInfo(@RequestParam String companyId){
        CompanyInfoVO companyInfoVO = companyService.getCompanyInfoById(companyId);
        return GraceJSONResult.ok(companyInfoVO);
    }


    /**
     * 运营端审核公司
     * @return
     */
    @PostMapping("/admin/doReview")
    public GraceJSONResult doReview(@RequestBody @Valid ReviewCompanyBO reviewCompanyBO){
        companyService.reviewCompany(reviewCompanyBO);
        if(reviewCompanyBO.getReviewStatus().equals(CompanyReviewStatus.SUCCESSFUL.type)){
            //将用户角色更改为2
            userMicroServiceFeign.changeUserToHR(reviewCompanyBO.getHrUserId());
        }
        //清除用户端的企业缓存
        redisTemplate.delete(REDIS_COMPANY_BASE_INFO + ":" + reviewCompanyBO.getCompanyId());
        return GraceJSONResult.ok();
    }

    //-------------------------saas端使用----------------------------------

    //saas端登录之后,要根据当前用户信息查询对应的公司信息
    @PostMapping("/info")
    public GraceJSONResult info(){
        Users user = JwtCurrentUserInterceptor.currentUser.get();
        CompanySimpleVO companyVO = getCompany(user.getHrInWhichCompanyId());
        return GraceJSONResult.ok(companyVO);
    }

    @PostMapping("/saas/moreInfo")
    public GraceJSONResult moreInfo(){
        Users user = JwtCurrentUserInterceptor.currentUser.get();
        String companyId = user.getHrInWhichCompanyId();
        CompanyInfoVO companyInfoVO = getCompanyMoreInfo(companyId);
        return GraceJSONResult.ok(companyInfoVO);
    }

    private CompanyInfoVO getCompanyMoreInfo(String companyId) {
        if(StringUtils.isBlank(companyId)){
            return null;
        }
        String jsonStr = redisTemplate.opsForValue().get(REDIS_COMPANY_MORE_INFO + ":" + companyId);
        if(StringUtils.isBlank(jsonStr)){
            //查询数据库，查到后放进redis
            Company company = companyService.getById(companyId);
            CompanyInfoVO companyInfoVO = new CompanyInfoVO();
            BeanUtils.copyProperties(company, companyInfoVO);
            companyInfoVO.setCompanyId(company.getId());
            //放入redis
            redisTemplate.opsForValue().set(REDIS_COMPANY_MORE_INFO + ":" + companyId, new Gson().toJson(companyInfoVO), 2 * 60, TimeUnit.SECONDS);
            return companyInfoVO;
        }else {
            return new Gson().fromJson(jsonStr, CompanyInfoVO.class);
        }
    }


    @PostMapping("/saas/getPhotos")
    public GraceJSONResult getSaasPhotos(){
        Users users = JwtCurrentUserInterceptor.currentUser.get();
        CompanyPhoto companyPhoto = companyService.getPhotos(users.getHrInWhichCompanyId());
        return GraceJSONResult.ok(companyPhoto);
    }
}



















